﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Windows.Forms;
using DM4;
using sscore;
using DevExpress.XtraGrid.Views.Base;
using sscore.Utils;
namespace DM4Client
{
    public partial class FrmMain
    {

        #region Mail Form Handlers
        private void btnAddLetterRuleClick(object sender, EventArgs e)
        {
            AddMailLettersRule();
        }

        private void btnDeleteLetterRuleClick(object sender, EventArgs e)
        {
            DeleteMailLettersRule();
        }


        private void DgMailTemplateFocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            RefreshOneMailTemplate();
        }

        private void DgMailSendersFocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            RefreshOneSender();
        }

        private void DgLettersFocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            RefreshOneLetter();
        }

        private void MailPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            switch (_fMails.tcMails.SelectedTabPageIndex)
            {
                case (int)MailActivePageIdx.Accounts:
                    RefreshMailAccounts();
                    break;
                case (int)MailActivePageIdx.Sender:
                    RefreshMailSendTemplates();
                    break;
                case (int)MailActivePageIdx.Listener:
                    RefreshSenders();
                    RefreshAllRules();
                    break;
                default: break;
            }
        }

        private void rbiAddMailItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (_fMails.tcMails.SelectedTabPageIndex)
            {
                case (int)MailActivePageIdx.Accounts:
                    AddEditMailAccount(false);
                    break;
                case (int)MailActivePageIdx.Sender:
                    AddEditMailTemplate(false);
                    break;
                case (int)MailActivePageIdx.Listener:
                    if (_fMails.gcSenders.Focused)
                        AddEditSender(false);
                    else if (_fMails.gcLetters.Focused)
                    {
                        AddEditLetter(false);
                    }
                    else if (_fMails.gcAllRules.Focused)
                    {
                        AddEditRule(false);
                    }
                    else if (_fMails.gcLetterRules.Focused)
                    {
                        //AddEditRule(_fMails.gcCheckRules, false);
                    }
                    break;
                default: break;
            }
        }

        private void rbiEditMailItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (_fMails.tcMails.SelectedTabPageIndex)
            {
                case (int)MailActivePageIdx.Accounts:
                    AddEditMailAccount();
                    break;
                case (int)MailActivePageIdx.Sender:
                    AddEditMailTemplate();
                    break;
                case (int)MailActivePageIdx.Listener:
                    if (_fMails.gcSenders.Focused)
                        AddEditSender();
                    else if (_fMails.gcLetters.Focused)
                        AddEditLetter();
                    else if (_fMails.gcAllRules.Focused)
                    {
                        AddEditRule();
                    }
                    else if (_fMails.gcLetterRules.Focused)
                    {
                        //AddEditRule(_fMails.gcCheckRules);
                    }
                    break;
                default: break;
            }
        }

        private void rbiRefreshMailItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (_fMails.tcMails.SelectedTabPageIndex)
            {
                case (int)MailActivePageIdx.Accounts:
                    RefreshMailAccounts();
                    break;
                case (int)MailActivePageIdx.Sender:
                    RefreshMailSendTemplates();
                    break;
                case (int)MailActivePageIdx.Listener:
                    // if (_fMails.gcSenders.Focused)
                    RefreshSenders();
                    //else if (_fMails.gcAllRules.Focused)
                    //    RefreshAllRules();
                    break;
                default: break;

            }
        }

        private void rbiDeleteMailItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (_fMails.tcMails.SelectedTabPageIndex)
            {
                case (int)MailActivePageIdx.Accounts:
                    DeleteMailAccount();
                    break;
                case (int)MailActivePageIdx.Sender:
                    DeleteMailTemplate();
                    break;
                case (int)MailActivePageIdx.Listener:
                    if (_fMails.gcSenders.Focused)
                        DeleteSender();
                    else if (_fMails.gcLetters.Focused)
                        DeleteLetter();
                    else if (_fMails.gcLetterRules.Focused)
                    {
                        //  AddEditRule( _fMails.gcGetRules, false);
                    }
                    else if (_fMails.gcAllRules.Focused)
                    {
                        //AddEditRule(_fMails.gcCheckRules, false);
                    }
                    break;
                default: break;
            }
        }

        private void rbiTestMailItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            BeginWait();
            try
            {

                switch (_fMails.tcMails.SelectedTabPageIndex)
                {
                    case (int)MailActivePageIdx.Sender:
                        try
                        {
                            Dictionary<string, string> macros = new Dictionary<string, string>
                                                           {
                                                               {"[subj some value]", " subjReplacedValue"},
                                                               {"[body value 1.1]", "1.1"},
                                                               {"[body value 1.2]", "1.2"},
                                                               {"[body value 2.1]", "2.1"},
                                                               {"[body value 2.2]", "2.2"}
                                                           };

                            List<MailSenderParameters> l = new List<MailSenderParameters>();
                            for (int i = 0; i < 3; i++)
                            {
                                l.Add(new MailSenderParameters("developer@sstudio.in.ua", "developer2@sstudio.in.ua", "test template", macros, 3));
                                //new MailSenderParameters("developer@sstudio.in.ua", "developer2@sstudio.in.ua", "testsubject", "testbody", 3);
                            }
                            OperationResult or = ExecuteDaemonCommand(MailSenderConsts.ModuleCode, MailSenderCommands.SendMail, l);

                            EndWait();
                            MessageBox.Show(this, "OperationResult Message: " + or.Message, MailSenderConsts.ModuleCode + " test success.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            EndWait();
                            MessageBox.Show(this, "Exception: " + ex.Message, String.Format("{0} test {1}", MailSenderConsts.ModuleCode, DmConsts.Error), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;
                    case (int)MailActivePageIdx.Listener:
                        try
                        {

                            MailListenerParameters param = new MailListenerParameters() { MailAccountIdForCheck = 5 };
                            param.LetterIds.Add(2);
                            OperationResult or = ExecuteDaemonCommand(MailListenerConsts.ModuleCode, MailListenerCommands.CheckMail, param);

                            EndWait();
                            MessageBox.Show(this, "OperationResult Message: " + or.Message, MailListenerConsts.ModuleCode + " test success.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            EndWait();
                            MessageBox.Show(this, "Exception: " + ex.Message, String.Format("{0} test {1}", MailListenerConsts.ModuleCode, DmConsts.Error), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;
                    default: break;
                }
                UpdateMainControlsState();
            }
            finally
            {
                EndWait();
            }
        }

        private void rbiStartMailItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            BeginWait();
            try
            {
                string moduleCode = null;
                switch (_fMails.tcMails.SelectedTabPageIndex)
                {
                    case (int)MailActivePageIdx.Sender:
                        moduleCode = MailSenderConsts.ModuleCode;
                        break;
                    case (int)MailActivePageIdx.Listener:
                        moduleCode = MailListenerConsts.ModuleCode;
                        break;
                    default: break;
                }

                if (!string.IsNullOrEmpty(moduleCode))
                    try
                    {
                        OperationResult or = StartDaemon(moduleCode);
                        EndWait();
                        MessageBox.Show(this, "OperationResult Message: " + or.Message, moduleCode + " start", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        EndWait();
                        MessageBox.Show(this, "Exception: " + ex.Message, String.Format("{0} start : {1}", moduleCode, DmConsts.Error), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                UpdateMainControlsState();
            }
            finally
            {
                EndWait();
            }
        }

        private void rbiStopMailItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            BeginWait();
            try
            {

                string moduleCode = null;
                switch (_fMails.tcMails.SelectedTabPageIndex)
                {
                    case (int)MailActivePageIdx.Sender:
                        moduleCode = MailSenderConsts.ModuleCode;
                        break;
                    case (int)MailActivePageIdx.Listener:
                        moduleCode = MailListenerConsts.ModuleCode;
                        break;
                    default: break;
                }

                if (!string.IsNullOrEmpty(moduleCode))
                    try
                    {
                        OperationResult or = StopDaemon(moduleCode);
                        EndWait();
                        MessageBox.Show(this, "OperationResult Message: " + or.Message, moduleCode + " stop.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        EndWait();
                        MessageBox.Show(this, "Exception: " + ex.Message, String.Format("{0} stop: {1}", moduleCode, DmConsts.Error), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                UpdateMainControlsState();
            }
            finally
            {
                EndWait();
            }
        }
        #endregion Mail Form Handlers

        #region MailAccounts
        private void DeleteMailAccount()
        {
            if (_fMails.gvAccounts.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
            {
                DataRow drs = _fMails.gvAccounts.GetDataRow(_fMails.gvAccounts.FocusedRowHandle);
                int maId = SysUtils.ConvertFromDBVal<int>(drs[CnMailAccounts.Id]);

                if (MessageBox.Show(this, String.Format("Delete mail account with id {0}?", maId), "Delete mail account",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    return;

                OperationResult or = FrmMain.DeleteMailAccount(maId);

                if (or.Result != DM4Consts.Ok)
                    MessageBox.Show(this, or.Message, DmConsts.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(this, "Mail account deleted", "Delete mail account", MessageBoxButtons.OK, MessageBoxIcon.Information);

                RefreshMailAccounts();
            }
        }

        private void AddEditMailAccount(bool edit = true)
        {
            DataRow drs = _fMails.gvAccounts.GetDataRow(_fMails.gvAccounts.FocusedRowHandle);
            if (edit && drs == null) return;

            int maId = edit ? SysUtils.ConvertFromDBVal<int>(drs[CnMailAccounts.Id]) : DM4Consts.DefaultNULLId;

            if (_fMails.gvAccounts.FocusedRowHandle == DevExpress.XtraGrid.GridControl.InvalidRowHandle && edit) return;

            using (AddEditForms.FrmAddEditMailAccount frmAddEdit = new AddEditForms.FrmAddEditMailAccount(maId))
            {
                DialogResult dr = frmAddEdit.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    if (!edit)
                        maId = frmAddEdit.Result.Result;

                    RefreshMailAccounts(maId);
                }
            }
        }

        private void RefreshMailAccounts(int accId = DM4Consts.DefaultNULLId)
        {
            try
            {
                int id = GetIdFromGridView(_fMails.gvAccounts, CnMailAccounts.Id, accId);
                try
                {
                    _fMails.dgAccounts.DataSource = null;

                    XMLInfo xi = FrmMain.GetMailAccountList();
                    DtMailAccounts = XMLInfo.FillTable(xi, DtMailAccounts);

                    _fMails.dgAccounts.DataMember = DtMailAccounts.TableName;
                    _fMails.dgAccounts.DataSource = DtMailAccounts;

                    _fMails.gvAccounts.BeginUpdate();
                    try
                    {
                        int rowHandle = _fMails.gvAccounts.LocateByValue(CnMailAccounts.Id, id);
                        // exiting the loop if no row is found 
                        if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                            _fMails.gvAccounts.FocusedRowHandle = rowHandle;
                        else
                            if (_fMails.gvAccounts.RowCount > 0)
                                _fMails.gvAccounts.MoveFirst();
                    }
                    finally
                    {
                        _fMails.gvAccounts.EndUpdate();
                    }
                    _fMails.dgAccounts.Focus();
                    UpdateMainControlsState();
                }
                catch (Exception ex)
                {
                    //SERVER IS DOWN!! NEED RECONNECT                   
                    WriteError(ex.Message);
                    LoginToService();
                }
            }
            catch (Exception ex)
            {
                WriteError(ex.Message);
            }
        }
        #endregion MailAccounts

        #region MailSendTemplates
        private void RefreshMailSendTemplates(int templateId = DM4Consts.DefaultNULLId)
        {
            _fMails.gvMailTemplates.FocusedRowChanged -= DgMailTemplateFocusedRowChanged;
            try
            {
                int id = GetIdFromGridView(_fMails.gvMailTemplates, CnMailSendTemplate.Id, templateId);
                try
                {
                    _fMails.dgMailTemplates.DataSource = null;

                    XMLInfo xi = GetMailSendTemplateList();
                    DtMailSendTemplates = XMLInfo.FillTable(xi, DtMailSendTemplates);

                    _fMails.dgMailTemplates.DataMember = DtMailSendTemplates.TableName;
                    _fMails.dgMailTemplates.DataSource = DtMailSendTemplates;

                    _fMails.gvMailTemplates.BeginUpdate();
                    try
                    {
                        int rowHandle = _fMails.gvMailTemplates.LocateByValue(CnMailSendTemplate.Id, id);
                        // exiting the loop if no row is found 
                        if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                            _fMails.gvMailTemplates.FocusedRowHandle = rowHandle;
                        else
                            if (_fMails.gvMailTemplates.RowCount > 0)
                                _fMails.gvMailTemplates.MoveFirst();

                        RefreshOneMailTemplate();
                        _fMails.dgMailTemplates.Focus();
                    }
                    finally
                    {
                        _fMails.gvMailTemplates.EndUpdate();
                    }

                    UpdateMainControlsState();
                }
                catch (Exception ex)
                {
                    //SERVER IS DOWN!! NEED RECONNECT                    
                    WriteError(ex.Message);
                    LoginToService();
                }
            }
            finally
            {
                _fMails.gvMailTemplates.FocusedRowChanged += DgMailTemplateFocusedRowChanged;
            }
        }

        private void RefreshOneMailTemplate()
        {
            //get datarow           
            int rowHandle = _fMails.gvMailTemplates.FocusedRowHandle;

            DataRow drs = _fMails.gvMailTemplates.GetDataRow(rowHandle);

            if (drs != null)
            {
                _stbMailSendTemplateSubject.Text = drs[CnMailSendTemplate.Subject].ToString();
                _stbMailSendTemplateBody.Text = drs[CnMailSendTemplate.Body].ToString();
            }
            try
            {
                string filePath = Path.Combine(WorkDir, "Tmp", "tmp.html");
                string text = drs[CnMailSendTemplate.Body].ToString();
                File.WriteAllText(filePath, text);
                _fMails.wbMailTemplateView.Navigate(filePath);
            }
            catch (Exception ex)
            {
                WriteError(ex.Message);
            }
            UpdateMainControlsState();
        }

        private void AddEditMailTemplate(bool edit = true)
        {
            DataRow drs = _fMails.gvMailTemplates.GetDataRow(_fMails.gvMailTemplates.FocusedRowHandle);
            if (edit && drs == null) return;

            int templateId = edit ? SysUtils.ConvertFromDBVal<int>(drs[CnMailSendTemplate.Id]) : DM4Consts.DefaultNULLId;

            if (_fMails.gvMailTemplates.FocusedRowHandle == DevExpress.XtraGrid.GridControl.InvalidRowHandle && edit) return;

            using (AddEditForms.FrmAddEditMailTemplate frmAddEdit = new AddEditForms.FrmAddEditMailTemplate(Prm, templateId))
            {
                DialogResult dr = frmAddEdit.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    if (!edit)
                        templateId = frmAddEdit.Result.Result;

                    RefreshMailSendTemplates(templateId);
                }
            }
        }

        private void DeleteMailTemplate()
        {
            if (_fMails.gvMailTemplates.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
            {
                DataRow drs = _fMails.gvMailTemplates.GetDataRow(_fMails.gvMailTemplates.FocusedRowHandle);
                int templateId = SysUtils.ConvertFromDBVal<int>(drs[CnMailSendTemplate.Id]);

                if (MessageBox.Show(this, String.Format("Delete letter template with id {0}?", templateId), "Delete letter template",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    return;

                OperationResult or = DeleteMailSendTemplate(templateId);

                if (or.Result != DM4Consts.Ok)
                    MessageBox.Show(this, or.Message, DmConsts.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(this, "Letter template deleted", "Delete letter template", MessageBoxButtons.OK, MessageBoxIcon.Information);

                RefreshMailSendTemplates();
            }
        }
        #endregion MailSendTemplates

        #region Mail Listener Check and Get Rules

        private void RefreshSenders(int entityId = DM4Consts.DefaultNULLId)
        {
            DataTable dt = DtMailSenders;
            DevExpress.XtraGrid.Views.Grid.GridView gv = _fMails.gvSenders;
            DevExpress.XtraGrid.GridControl gc = _fMails.gcSenders;
            string idColumnName = CnMailSenders.Id;
            FocusedRowChangedEventHandler frceh = DgMailSendersFocusedRowChanged;

            gv.FocusedRowChanged -= frceh;
            try
            {
                int id = GetIdFromGridView(gv, idColumnName, entityId);
                try
                {
                    gc.DataSource = null;

                    XMLInfo xi = FrmMain.GetMailSendersList();//!!!!!
                    dt = XMLInfo.FillTable(xi, dt);

                    gc.DataMember = dt.TableName;
                    gc.DataSource = dt;
                    gv.BeginUpdate();
                    try
                    {
                        int rowHandle = gv.LocateByValue(idColumnName, id);
                        if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                            gv.FocusedRowHandle = rowHandle;
                        else
                            if (gv.RowCount > 0)
                                gv.MoveFirst();

                        RefreshOneSender();//!!!!!
                    }
                    finally
                    {
                        gv.EndUpdate();
                    }

                    gc.Focus();
                    UpdateMainControlsState();
                }
                catch (Exception ex)
                {
                    WriteError(ex.Message);
                    LoginToService();
                }
            }
            finally
            {
                gv.FocusedRowChanged += frceh;
            }
        }

        private void RefreshOneSender()
        {
            int senderId = GetIdFromGridView(_fMails.gvSenders, CnMailSenders.Id);

            DataTable dt = DtLetters;
            DevExpress.XtraGrid.GridControl gc = _fMails.gcLetters;
            DevExpress.XtraGrid.Views.Grid.GridView gv = _fMails.gvLetters;
            string idColumnName = CnMailLetters.Id;
            FocusedRowChangedEventHandler frceh = DgLettersFocusedRowChanged;

            gv.FocusedRowChanged -= frceh;
            try
            {
                int id = GetIdFromGridView(gv, idColumnName);
                try
                {
                    gc.DataSource = null;
                    XMLInfo xi = FrmMain.GetLettersList(String.Format("where {0} = {1}"
                        , CnMailLetters.SenderId, senderId));//!!!!!
                    dt = XMLInfo.FillTable(xi, dt);

                    gc.DataMember = dt.TableName;
                    gc.DataSource = dt;
                    gv.BeginUpdate();
                    try
                    {
                        int rowHandle = gv.LocateByValue(idColumnName, id);
                        if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                            gv.FocusedRowHandle = rowHandle;
                        else
                            if (gv.RowCount > 0)
                                gv.MoveFirst();

                        RefreshOneLetter();//!!!!!
                    }
                    finally
                    {
                        gv.EndUpdate();
                    }
                    UpdateMainControlsState();
                }
                catch (Exception ex)
                {
                    WriteError(ex.Message);
                    LoginToService();
                }
            }
            finally
            {
                gv.FocusedRowChanged += frceh;
            }
        }

        private void RefreshOneLetter()
        {
            int letterId = GetIdFromGridView(_fMails.gvLetters, CnMailLetters.Id);

            DataTable dt = DtMailLettersRules;
            DevExpress.XtraGrid.GridControl gc = _fMails.gcLetterRules;
            DevExpress.XtraGrid.Views.Grid.GridView gv = _fMails.gvLetterRules;
            string idColumnName = CnMailRules.Id;

            int id = GetIdFromGridView(gv, idColumnName);
            try
            {
                gc.DataSource = null;

                XMLInfo xi = FrmMain.GetMailLettersRulesList(letterId);
                dt = XMLInfo.FillTable(xi, dt);

                gc.DataMember = dt.TableName;
                gc.DataSource = dt;
                gv.BeginUpdate();
                try
                {
                    int rowHandle = gv.LocateByValue(idColumnName, id);
                    if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                        gv.FocusedRowHandle = rowHandle;
                    else
                        if (gv.RowCount > 0)
                            gv.MoveFirst();
                }
                finally
                {
                    gv.EndUpdate();
                }
                UpdateMainControlsState();
            }
            catch (Exception ex)
            {
                WriteError(ex.Message);
                LoginToService();
            }
        }

        private void RefreshAllRules(int entityId = DM4Consts.DefaultNULLId)
        {
            //int letterId = GetIdFromGridView(_fMails.gvLetters, CnMailLetters.Id);
            // _fMails.gcGetRules.DataSource = null;

            DevExpress.XtraGrid.GridControl gc = _fMails.gcAllRules;
            DevExpress.XtraGrid.Views.Grid.GridView gv = _fMails.gvAllRules;
            DataTable dt = DtMailRules;
            string idColumnName = CnMailRules.Id;
            int id = GetIdFromGridView(gv, idColumnName, entityId);

            try
            {
                gc.DataSource = null;
                XMLInfo xi = FrmMain.GetMailRulesList();
                dt = XMLInfo.FillTable(xi, dt);

                gc.DataMember = dt.TableName;
                gc.DataSource = dt;
                gv.BeginUpdate();
                try
                {
                    int rowHandle = gv.LocateByValue(idColumnName, id);
                    if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                        gv.FocusedRowHandle = rowHandle;
                    else
                        if (gv.RowCount > 0)
                            gv.MoveFirst();
                }
                finally
                {
                    gv.EndUpdate();
                }
                UpdateMainControlsState();
            }
            catch (Exception ex)
            {
                WriteError(ex.Message);
                LoginToService();
            }

            //try
            //{

            //    XMLInfo xi = FrmMain.GetMailRulesList();
            //    DtMailLettersRules = XMLInfo.FillTable(xi, DtMailLettersRules);
            //}
            //catch (Exception ex)
            //{
            //    WriteError(ex.Message);
            //    LoginToService();
            //}       
        }

        private void AddEditSender(bool edit = true)
        {
            DevExpress.XtraGrid.Views.Grid.GridView gv = _fMails.gvSenders;
            string idColumnName = CnMailSenders.Id;
            string valueColumnName = CnMailSenders.Mail;
            int id = DM4Consts.DefaultNULLId;
            string value = "";

            if (edit && gv.RowCount > 0)
            {
                DataRow drs = gv.GetDataRow(gv.FocusedRowHandle);
                id = SysUtils.ConvertFromDBVal<int>(drs[idColumnName]);
                value = SysUtils.ConvertFromDBVal<string>(drs[valueColumnName]);
            }
            if (edit && id == DM4Consts.DefaultNULLId) return;


            if (TextBoxForm.Show(edit ? ("Edit sender " + id) : "New sender adding", "Mail", ref value) == DM4Consts.Ok)
            {
                try
                {
                    OperationResult or = new OperationResult();
                    if (edit)
                        or = FrmMain.EditMailSender(id, value);
                    else or = FrmMain.AddMailSender(value);
                    RefreshSenders();
                }
                catch (Exception ex)
                {
                    FrmMain.WriteError((edit ? "Error of letter editing" : "Error of letter creating") + Environment.NewLine + ex.Message);
                }
            }
        }

        private void DeleteSender()
        {
            DevExpress.XtraGrid.Views.Grid.GridView gv = _fMails.gvSenders;
            string idColumnName = CnMailSenders.Id;

            if (gv.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
            {
                int id = GetIdFromGridView(gv, idColumnName);
                if (MessageBox.Show(this, String.Format("Delete sender with id {0} and all related records?", id), "Delete sender",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    return;

                OperationResult or = DeleteMailSender(id);

                if (or.Result != DM4Consts.Ok)
                    MessageBox.Show(this, or.Message, DmConsts.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(this, "Sender deleted", "Delete sender", MessageBoxButtons.OK, MessageBoxIcon.Information);

                RefreshSenders();
            }
        }

        private void AddEditLetter(bool edit = true)
        {
            //-----------get sender for letter-----------------------------------
            int senderId = DM4Consts.DefaultNULLId;
            string sender = "";
            if (_fMails.gvSenders.RowCount > 0)
            {
                DataRow drs = _fMails.gvSenders.GetDataRow(_fMails.gvSenders.FocusedRowHandle);
                senderId = SysUtils.ConvertFromDBVal<int>(drs[CnMailSenders.Id]);
                sender = SysUtils.ConvertFromDBVal<string>(drs[CnMailSenders.Mail]);
            }
            if (senderId == DM4Consts.DefaultNULLId) return;

            //-----------get letter id and description----------------------------
            DevExpress.XtraGrid.Views.Grid.GridView gv = _fMails.gvLetters;
            string idColumnName = CnMailLetters.Id;
            string valueColumnName = CnMailLetters.Description;
            int id = DM4Consts.DefaultNULLId;
            string value = "";

            if (edit && gv.RowCount > 0)
            {
                DataRow drs = gv.GetDataRow(gv.FocusedRowHandle);
                id = SysUtils.ConvertFromDBVal<int>(drs[idColumnName]);
                value = SysUtils.ConvertFromDBVal<string>(drs[valueColumnName]);
            }
            if (edit && id == DM4Consts.DefaultNULLId) return;


            string caption = String.Format("{0} for sender: {1}",
                (edit ? ("Edit letter" + id) : "New letter adding"),
                sender);

            if (TextBoxForm.Show(caption, "Description", ref value) == DM4Consts.Ok)
            {
                try
                {
                    OperationResult or = new OperationResult();
                    if (edit)
                        or = FrmMain.EditLetter(id, senderId, value);
                    else or = FrmMain.AddLetter(senderId, value);

                    RefreshSenders(senderId);
                    gv.Focus();
                    UpdateMainControlsState();
                }
                catch (Exception ex)
                {
                    FrmMain.WriteError((edit ? "Error of letter editing" : "Error of letter creating") + Environment.NewLine + ex.Message);
                }
            }
        }

        private void DeleteLetter()
        {
            DevExpress.XtraGrid.Views.Grid.GridView gv = _fMails.gvLetters;
            string idColumnName = CnMailLetters.Id;


            if (gv.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
            {
                int id = GetIdFromGridView(gv, idColumnName);

                if (MessageBox.Show(this, String.Format("Delete letter with id {0}  and all related records?", id), "Delete letter",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    return;

                OperationResult or = DeleteLetter(id);

                if (or.Result != DM4Consts.Ok)
                    MessageBox.Show(this, or.Message, DmConsts.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(this, "Letter deleted", "Delete letter", MessageBoxButtons.OK, MessageBoxIcon.Information);

                int senderId = GetIdFromGridView(_fMails.gvSenders, CnMailSenders.Id);
                RefreshSenders(senderId);
            }

        }

        private void AddEditRule(bool edit = true)
        {
            DataRow drs = _fMails.gvAllRules.GetDataRow(_fMails.gvAllRules.FocusedRowHandle);
            if (edit && drs == null) return;

            int id = edit ? SysUtils.ConvertFromDBVal<int>(drs[CnMailRules.Id]) : DM4Consts.DefaultNULLId;

            if (_fMails.gvAllRules.FocusedRowHandle == DevExpress.XtraGrid.GridControl.InvalidRowHandle && edit) return;

            using (AddEditForms.FrmAddEditMailRule frmAddEdit = new AddEditForms.FrmAddEditMailRule(id))
            {
                DialogResult dr = frmAddEdit.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    if (!edit)
                        id = frmAddEdit.Result.Result;

                    RefreshAllRules(id);
                }
            }
        }

        private void AddMailLettersRule()
        {
            int letterId = GetIdFromGridView(_fMails.gvLetters, CnMailLetters.Id);

            DevExpress.XtraGrid.Views.Grid.GridView gv = _fMails.gvAllRules;
            string idColumnName = CnMailRules.Id;

            if (gv.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
            {
                int id = GetIdFromGridView(gv, idColumnName);

                if (MessageBox.Show(this, String.Format("Add rule with id {0} for letter {1}?", id, letterId), "Add mail rule for letter.",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    return;

                OperationResult or = AddMailLettersRule(letterId, id);

                if (or.Result > 0)
                    MessageBox.Show(this, "Mail rule for letter added.", "Add mail rule for letter.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                    MessageBox.Show(this, or.Message, DmConsts.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);

                RefreshOneLetter();
            }
        }

        private void DeleteMailLettersRule()
        {
            int letterId = GetIdFromGridView(_fMails.gvLetters, CnMailLetters.Id);

            DevExpress.XtraGrid.Views.Grid.GridView gv = _fMails.gvLetterRules;
            string idColumnName = CnMailRules.Id;


            if (gv.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
            {
                int ruleId = GetIdFromGridView(gv, idColumnName);

                if (MessageBox.Show(this, String.Format("Delete rule with id {0} for letter {1}?", ruleId, letterId), "Delete mail rule for letter.",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    return;

                OperationResult or = DeleteMailLettersRule(letterId, ruleId);

                if (or.Result != DM4Consts.Ok)
                    MessageBox.Show(this, or.Message, DmConsts.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(this, "Mail rule for letter deleted.", "Delete mail rule for letter.", MessageBoxButtons.OK, MessageBoxIcon.Information);

                RefreshOneLetter();
            }
        }
        #endregion
        private static int GetIdFromGridView(DevExpress.XtraGrid.Views.Grid.GridView gv, string idColumnName, int entityId = DM4Consts.DefaultNULLId)
        {
            int id = DM4Consts.DefaultNULLId;
            if (entityId == DM4Consts.DefaultNULLId)
            {
                if (gv.RowCount > 0)
                {
                    DataRow drs = gv.GetDataRow(gv.FocusedRowHandle);
                    id = SysUtils.ConvertFromDBVal<int>(drs[idColumnName]);
                }
            }
            else
                id = entityId;

            return id;
        }

    }
}
